package com.entrogy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.entrogy.api.ThdidPersonApi;
import com.entrogy.bean.*;
import com.entrogy.listener.ImportCourseListener;
import com.entrogy.service.*;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.utils.*;
import com.entrogy.utils.constants.Constants;
import com.entrogy.utils.constants.ErrorEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName NginxTestController
 * @Description TODO
 * @Author luoxingjiang
 * @Date 2019/7/19 0019 上午 11:56
 * @Version 1.0
 **/
@RestController
@RequestMapping(value = "/studentPush")
@Api(description = "录入信息")
public class UtilsController {

    private static final Logger logger = LoggerFactory.getLogger(UtilsController.class);

    @Value("${image.root.path}")
    private String baseImage;

    @Autowired
    private THDio thdio;

    @Autowired
    private StudentService studentService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private MachineService machineService;

    @Autowired
    private UserService userService;

    @Autowired
    private ClassService classService;

    @Autowired
    private ParentService parentService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private UtilsService utilsService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ThdidPersonApi thdidPersonApi;

    @Autowired
    private EasyExcelUtil easyExcelUtil;

    @Autowired
    private CourseSystemService courseSystemService;

    @Autowired
    private ExamService examService;

    @Autowired
    private StudentScoreService studentScoreService;


    @PostMapping(value = "/student-authorization")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "推送的设备类别，0表示进门设备，1表示出门设备，不填表示全部设备", name = "isOut", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "是否需要根据年级的时间规则推送，0表示推送任意时间，1表示按年级的静态时间推送", name = "isStaticCycle", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "批量查询出某个学校的学生信息并推送到该学校的设备（必须事先在学校-设备表内为该学校分配设备）")
    public Msg studentBatchPush(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId, Integer isOut, Integer isStaticCycle) {
        List<StudentEntity> studentList = studentService.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, null, null, null);
        if (studentList.size() == 0) {
            return Msg.fail(ErrorEnum.E_101, "没有任何学生被选中！");
        }
        if (schoolCode == null && studentId != null) {
            schoolCode = studentList.get(0).getSchoolCode();
        }
        //获取实义德后台地址
        SchoolThdidUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        String deviceIds = getSchoolDeviceIdString(schoolCode, isOut);
        for (StudentEntity studentEntity : studentList) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (studentEntity.getAllowTime() != null && !studentEntity.getAllowTime().equals("000")) {
                // 获得该年级某一种时间段规则
                StaticCycleEntity staticCycle = classService.getStaticCycle(studentEntity.getGradeId(), schoolCode, studentEntity.getAllowTime());
                Integer cycleId = isStaticCycle == 0 ? 1 : staticCycle.getCycleId();
                String cycleName = isStaticCycle == 0 ? "全体All" : staticCycle.getCycleName();
                if (!StrUtils.isNullOrEmpty(deviceIds)) {
                    int personType = 0; //0-修改新增或更新人员 1--请假类的
                    int thdId = studentEntity.getStudentThdid();//实义德ID
                    if (thdId != 0) {
                        ChangePersonTimeThread changePersonTimeThread = new ChangePersonTimeThread(deviceIds, thdId + "", 1,
                                cycleId, cycleName, 999999, 111111111L, 99999999999L, "修改学生", personType, schoolThididUrl.getPathUrl(), schoolThididUrl.getAccessToken());
                        changePersonTimeThread.start();
                    }
                }
            }
        }
        return Msg.success();
    }

    @PostMapping(value = "/add-student-all")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "批量查询出某个些学生信息添加到实义德后台并推送通行到该学校的大门的设备（必须事先在学校-设备表内为该学校分配设备）")
    public Msg studentBatchAddAndPush(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
        List<StudentEntity> studentList = studentService.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, null, null, null);
        logger.info("开始向实义德后台添加学生=》学生总计：" + studentList.size() + "人");
        for (StudentEntity studentEntity : studentList) {
            thdidPersonApi.asyncAddStudent(studentEntity, schoolCode, Constants.THDID_AI16);
        }
        return Msg.success();
    }

    @PostMapping(value = "/add-teacher-authorization")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "教师id", name = "teacherIds", dataType = "String", paramType = "query", allowMultiple = true),
    })
    @ApiOperation(value = "批量查询出某个些教师信息添加到实义德后台并推送通行到该学校的大门的设备（必须事先在学校-设备表内为该学校分配设备）")
    public Msg teacherBatchAddAndPush(Integer schoolCode, Integer gradeId, Integer classId, String[] teacherIds) {
        List<UserEntity> teacherList = userService.listSchoolTeacher(schoolCode, gradeId, classId, teacherIds, null);
        for (UserEntity userEntity : teacherList) {
            TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
            teacher.setTeacherId(userEntity.getId()).setIdNumber(userEntity.getIdNumber()).setIcNumber(userEntity.getIcNumber())
                    .setPhoto(userEntity.getPhoto()).setGender(userEntity.getSex()).setTeacherName(userEntity.getName()).setTeacherThdidAi06Id(userEntity.getUserThdid())
                    .setTeacherThdidAi16Id(userEntity.getTeacherThdidAi16Id());
            thdidPersonApi.addTeacherToAll(teacher, schoolCode);
        }
        return Msg.success();
    }

    @PostMapping(value = "/batch-insert-parent")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "查询出学生信息（带有家长电话号码）后插入家长数据")
    public Msg batchInsertParentByPhone(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
        List<StudentEntity> failStudentList = studentService.batchInsertParentByPhone(schoolCode, gradeId, classId, studentId);
        return Msg.success().add("failStudentList", failStudentList);
    }


    private String getSchoolDeviceIdString(Integer schoolCode, Integer isOut) {
        MachineEntity machine = new MachineEntity();
        machine.setSchoolCode(schoolCode).setIsout(isOut).setDeviceModel(Constants.THDID_AI06);
        List<String> deviceIdList = machineService.listMachineId(machine);// 获取该学校的所有闸机设备
        //学校全部设备id字符串
        StringBuilder deviceIds = new StringBuilder();
        for (String deviceId : deviceIdList) {
            deviceIds.append(",").append(deviceId);
        }
        if (deviceIds.length() > 0) {
            deviceIds = new StringBuilder(deviceIds.substring(1));
        }
        return deviceIds.toString();
    }

    @PostMapping(value = "/allot-student-dorm")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "批量查询出某个学校的学生信息分配到寝室")
    public Msg allotStudentDorm(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
        List<StudentEntity> studentList = studentService.allotStudentDorm(schoolCode, gradeId, classId, studentId);
        return Msg.success().add("studentList", studentList);
    }

    @PostMapping(value = "/init-student")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "初始化学生数据")
    public Msg initStudentData(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
        List<StudentEntity> studentList = studentService.initStudentData(schoolCode, gradeId, classId, studentId);
        return Msg.success().add("studentList", studentList);
    }

    @PostMapping(value = "/delete-student")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "批量删除数据和实义德后台的学生信息")
    public Msg batchDeleteStudent(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
//        List<StudentEntity> studentList = studentService.listSchoolStudent();
//        if (studentList.size() == 0){
//            return Msg.fail(ErrorEnum.E_101, "没有任何学生被选中！");
//        }
//        if (schoolCode == null && studentId != null){
//            schoolCode = studentList.get(0).getSchoolCode();
//        }
//        //获取实义德后台地址
//        SchoolThididUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode);
//        for (StudentEntity studentEntity : studentList) {
//            int thdId = studentEntity.getStudentThdid();//实义德ID
//            JSONObject params = new JSONObject();
//            params.put("personnel_id", thdId);
//            params.put("type", 1);
//            if (thdId != 0){
//                JSONObject res = thdio.THD_interface(schoolThididUrl.getPathUrl(), "/personnel/delete", params, false);
//                logger.info("删除结果=>" + res.toString());
//                if (res.getInt("code") == 0){
//                    // 删除数据库的学生
//                    boolean result = studentService.deleteStudent(schoolCode, null, null, studentEntity.getId());
//                }
//            }
//        }
        return Msg.success();
    }

    @PostMapping(value = "/check-student")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "学生id", name = "studentId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "查询人员是否在实义德后台")
    public Msg checkStudent(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
        List<StudentEntity> studentList = studentService.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, null, null, null);
        List<StudentEntity> failStudentList = new ArrayList<>();
        if (studentList.size() == 0) {
            return Msg.fail(ErrorEnum.E_101, "没有任何学生被选中！");
        }
        if (schoolCode == null && studentId != null) {
            schoolCode = studentList.get(0).getSchoolCode();
        }
        // 获取实义德后台地址
        SchoolThdidUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        for (StudentEntity studentEntity : studentList) {
            int thdId = studentEntity.getStudentThdid();//实义德ID
            if (thdId != 0) {
                JSONObject params = new JSONObject();
                params.put("personnel_id", thdId);
                JSONObject res = thdio.THD_interface(schoolThididUrl.getPathUrl(), "/personnel/info", params, true, schoolThididUrl.getAccessToken());
                logger.info("查询结果=>" + res.toString());
                if (res.getInt("code") != 0) {
                    // 实义德没有的学生
                    failStudentList.add(studentEntity);
                    // 更新该学生的实义德id为0
                    studentService.updateStudentThdid(studentEntity.getId(), thdId);
                }
            }
        }
        return Msg.success().add("failStudentList", failStudentList);
    }


    @PostMapping(value = "/delete-repeat-parent")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "删除某个学校的重复家长数据")
    public Msg deleteRepeatParent(Integer schoolCode) {
        boolean result = parentService.deleteRepeatParent(schoolCode);
        return Msg.success();
    }

    @PostMapping(value = "/reset-student-parent-phone")
    @ApiOperation(value = "还原学生家长电话号码")
    public Msg resetStudentParentPhone() {
//        boolean result = parentService.resetStudentParentPhone();
        boolean result = parentService.updateParentWeixinInformation();
        return Msg.success();
    }

    @PostMapping(value = "/change-teacher-group")
    @ApiOperation(value = "更换老师分组")
    public Msg changeTeacherGroup(Integer schoolCode) {
        //获取实义德后台地址
        SchoolThdidUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        List<UserEntity> failTeacherList = new ArrayList<>();
        List<UserEntity> teacherList = userService.listSchoolTeacher(schoolCode, null, null, null, null);
        for (UserEntity userEntity : teacherList) {
            int thdId = userEntity.getUserThdid();//实义德ID
            JSONObject params = new JSONObject();
            params.put("personnel_id", thdId);
            params.put("group_id", schoolThididUrl.getTeacherGroupId());
            if (thdId != 0) {
                JSONObject res = thdio.THD_interface(schoolThididUrl.getPathUrl(), "/personnel/move_group", params, false, schoolThididUrl.getAccessToken());
                logger.info("移动分组结果=>" + res.toString());
                if (res.getInt("code") != 0) {
                    // 实义德没有的学生
                    failTeacherList.add(userEntity);
                }
            }
        }

        return Msg.success().add("failTeacherList", failTeacherList);
    }

    @PostMapping(value = "/init-course")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "年级id", name = "gradeId", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "班级id", name = "classId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "初始化课程数据")
    public Msg initCourseData(Integer schoolCode, Integer gradeId, Integer classId) {
        boolean result = courseService.initCourseData(schoolCode, gradeId, classId);
        return Msg.success();
    }

    @PostMapping(value = "/change-position")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "单职位切换多职位数据迁移")
    public Msg changePosition(Integer schoolCode) {
        List<UserEntity> userList = userService.listSchoolTeacher(schoolCode, null, null, null, null);
        List<UserEntity> failTeacherList = new ArrayList<>();
        for (UserEntity userEntity : userList) {
            List<PositionEntity> positionList = new ArrayList<>();
            PositionEntity positionEntity = positionService.getPositionByPid(schoolCode, userEntity.getpId());
            if (positionEntity == null) {
                failTeacherList.add(userEntity);
                continue;
            }
            positionList.add(positionEntity);
            boolean result = positionService.InsertUserPositionInfos(userEntity.getId(), positionList);
        }
        return Msg.success().add("failTeacherList", failTeacherList);
    }

    @PostMapping(value = "/import-teacher")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "默认角色id", name = "roleId", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "导入教师数据")
    public Msg importTeacher(Integer schoolCode, Integer roleId) {
        List<UserEntity> failTeacherList = userService.importTeacher(schoolCode, roleId);
        return Msg.success().add("failTeacherList", failTeacherList);
    }

    @PostMapping(value = "/reset-multiple-name-student-photo")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校id", name = "schoolCode", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "校正同名学生的照片问题")
    public Msg resetMultipleNameStudentPhoto(Integer schoolCode) {
        List<StudentEntity> failStudentList = utilsService.resetMultipleNameStudentPhoto(schoolCode);
        return Msg.success().add("failStudentList", failStudentList);
    }


    @PostMapping(value = "/temp-push-time")
    @ApiOperation(value = "临时推送权限")
    public Msg tempPushTime(Integer schoolCode, Integer[] gradeIds, Integer classId, Integer cycleId, String allowTime) {
        String studentIdStr = "";
        for (Integer gradeId : gradeIds) {
            List<StudentEntity> studentList = studentService.listSchoolAllStudent(schoolCode, gradeId, classId, null, null, null, allowTime);
            for (StudentEntity studentEntity : studentList) {
                int thdid = studentEntity.getStudentThdid();
                if (thdid != 0) {
                    studentIdStr += "," + thdid;
                }
            }
        }
        String schoolDeviceIdString = getSchoolDeviceIdString(schoolCode, 1);
        SchoolThdidUrlEntity schoolThdidUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        if (schoolThdidUrl != null)
            new ChangePersonTimeThread(schoolDeviceIdString, studentIdStr.substring(1), 0, 0, "", 1000000, 111111111L,
                99999999999L, "", 0, schoolThdidUrl.getPathUrl(), schoolThdidUrl.getAccessToken()).start();
        return Msg.success();
    }


    @PostMapping(value = "/temp-push-message")
    @ApiOperation(value = "临时推送消息")
    public Msg tempPushMessage(Integer schoolCode, Integer[] gradeIds, Integer classId, Integer studentId) {
        List<StudentEntity> studentList = studentService.listSchoolAllStudent(schoolCode, null, classId, studentId, null, null, null);
        List<JSONObject> jsonObjectList = new ArrayList<>();

        SchoolThdidUrlEntity schoolThdidUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        for (StudentEntity studentEntity : studentList) {
            if (studentEntity.getAllowTime().equals("000") || studentEntity.getStudentThdid() == 0) {
                continue;
            }
            JSONObject params = new JSONObject();
            params.put("page", 1);
            params.put("amount", 10);
            params.put("keyword", studentEntity.getStudentName());
            params.put("identify_start_time", 1574024400);
            params.put("identify_end_time", 1574042400);
            JSONObject res = thdio.THD_interface(schoolThdidUrl.getPathUrl(), "/record/list", params, true, schoolThdidUrl.getAccessToken());
            JSONArray jsonArray = res.getJSONObject("data").getJSONArray("record_list");
            JSONObject passRecord;
            if (jsonArray.size() > 0) {
                passRecord = jsonArray.getJSONObject(0);
            } else {
                logger.error("学生=>" + studentEntity.getStudentName() + "没有流水记录");
                continue;
            }
            passRecord.put("person_name", studentEntity.getStudentName());
            passRecord.put("person_id", studentEntity.getStudentThdid());
            jsonObjectList.add(passRecord);

//            com.alibaba.fastjson.JSONObject passRecord = (com.alibaba.fastjson.JSONObject)com.alibaba.fastjson.JSONObject.parse("{\n" +
//                    "        \"personnel_name\": \"李心新\",\n" +
//                    "        \"identify_ts\": 1566283879,\n" +
//                    "        \"identify_type\": 0,\n" +
//                    "        \"device_name\": \"510107000_sszx_1dm2\",\n" +
//                    "        \"identify_compare\": 0.982792,\n" +
//                    "        \"personnel_id\": 652,\n" +
//                    "        \"thumbnail_image\": \"\",\n" +
//                    "        \"record_id\": 4998,\n" +
//                    "        \"identify_image\": \"\",\n" +
//                    "        \"device_id\": 699,\n" +
//                    "        \"person_name\": \"李心新\",\n" +
//                    "        \"person_id\": 7295\n" +
//                    "      }");

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject jsonObj = JSONObject.fromObject(passRecord);
            HttpEntity<String> formEntity = new HttpEntity<>(jsonObj.toString(), headers);
            String result = restTemplate.postForObject("http://schoolyard.face2id.com/studentrecord/check", formEntity, String.class);

            if (result.contains("0")) {
                logger.info("学生=>" + studentEntity.getStudentName() + "家长信息推送成功！");
            }
        }
        return Msg.success().add("jsonObjectList", jsonObjectList);
    }

    @PostMapping(value = "/move-group-information")
    @ApiOperation(value = "迁移三原群组数据")
    public Msg moveGroupInformation() {
        return Msg.success();
    }


//    @PostMapping(value = "/move-group-information")
//    @ApiOperation(value = "迁移三原群组数据")
//    public Msg moveGroupInformation(){
//        return Msg.success();
//    }

    @PostMapping(value = "/importCourse")
    @ApiOperation(value = "导入选课系统中的课程信息")
    public Msg testAddStudent() {
        String fileName = "D:\\学校信息\\三原外国语\\2020选修课用表（最新版）.xlsx";
        List<ImportCourseEntity> failImportCourseList = easyExcelUtil.resolveExcelWithCourse(fileName, courseSystemService, utilsService, restTemplate);
        return Msg.success().add("failImportCourseList", failImportCourseList);
    }

    @GetMapping(value = "/listTemperature")
    @ApiOperation(value = "查询所有学校测温后台的通行记录")
    public Msg listTemperature() {
        JSONArray jsonArray = thdidPersonApi.listTemperature();
        return Msg.success().add("jsonArray", jsonArray);
    }

    @GetMapping(value = "/moveExamData")
    @ApiOperation(value = "迁移三原成绩数据")
    public Msg moveExamData() {
        Map<Integer, Integer> subjectListMap = new HashMap<>();
        subjectListMap.put(1, 179);
        subjectListMap.put(2, 180);
        subjectListMap.put(3, 181);
        subjectListMap.put(4, 182);
        subjectListMap.put(5, 183);
        subjectListMap.put(6, 184);
        subjectListMap.put(7, 185);
        subjectListMap.put(8, 186);
        subjectListMap.put(9, 187);
        List<com.alibaba.fastjson.JSONObject> examList = utilsService.listSanYuanExam();
        for (com.alibaba.fastjson.JSONObject jsonObject : examList) {
            ExamEntity exam = new ExamEntity();
            exam.setUserId("11571797615086");
            exam.setSchoolCode(510182006);
            exam.setExamTime(jsonObject.getDate("exam_time"));
            exam.setExamName(jsonObject.getString("exam_name"));
            String gradeId = jsonObject.getString("course_id");
            Integer grade = Integer.valueOf(gradeId.substring(0, 2) + (Integer.valueOf(gradeId.substring(2,3)) - 1) + gradeId.substring(3));
            exam.setGradeId(grade);
            String[] subjectList = jsonObject.getString("subjectlist").split(",");
            List<Integer> courseIds = new ArrayList<>();
            for (int i = 0; i < subjectList.length; i++) {
                if (subjectListMap.containsKey(Integer.valueOf(subjectList[i]))){
                    courseIds.add(subjectListMap.get(Integer.valueOf(subjectList[i])));
                }
            }
            exam.setCourseIds(courseIds);
            List<Integer> classIds = new ArrayList<>();
            String[] classList = jsonObject.getString("classlist").split(",");
            for (String classId : classList) {
                Integer temp = Integer.valueOf(classId.substring(0, 2) + (Integer.valueOf(classId.substring(2,3)) - 1) + classId.substring(3));
                classIds.add(temp);
            }
            exam.setClassIds(classIds);
            logger.info("当前迁移的考试为：{}", exam);
            //生成该次考试成绩表存储的表名,存储的表名规则为exam_score+当前年份+当前月份
            Date currentTime = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
            //根据日期生成表名
            String scoreTableName = ScoreTableNameUtil.createScoreTableName(dateFormat.format(currentTime));
            exam.setTableName(scoreTableName);
            Integer examId = examService.addExam(exam);
            List<com.alibaba.fastjson.JSONObject> scoreList = utilsService.listScore(jsonObject.getString("table_name"));
            ArrayList<StudentCourseScoreEntity> studentCourseScoreEntities = new ArrayList<>();
            for (com.alibaba.fastjson.JSONObject scoreObject : scoreList) {
                String classIdStr = scoreObject.getString("course_id");
                Integer classId = Integer.valueOf(classIdStr.substring(0, 2) + (Integer.valueOf(classIdStr.substring(2,3)) - 1) + classIdStr.substring(3));
                // 查询学生id
                List<Integer> studentIds = studentService.getStudentId(scoreObject.getString("stu_name"), classId, 510182006);
                if (studentIds.size() > 0){
                    StudentCourseScoreEntity studentCourseScore1 = new StudentCourseScoreEntity();
                    studentCourseScore1.setExamId(examId);
                    studentCourseScore1.setStudentId(studentIds.get(0));
                    studentCourseScore1.setScore(scoreObject.getDouble("subject1"));
                    studentCourseScore1.setCourseId(179);
                    studentCourseScoreEntities.add(studentCourseScore1);

                    StudentCourseScoreEntity studentCourseScore2 = new StudentCourseScoreEntity();
                    studentCourseScore2.setExamId(examId);
                    studentCourseScore2.setStudentId(studentIds.get(0));
                    studentCourseScore2.setScore(scoreObject.getDouble("subject2"));
                    studentCourseScore2.setCourseId(180);
                    studentCourseScoreEntities.add(studentCourseScore2);

                    StudentCourseScoreEntity studentCourseScore3 = new StudentCourseScoreEntity();
                    studentCourseScore3.setExamId(examId);
                    studentCourseScore3.setStudentId(studentIds.get(0));
                    studentCourseScore3.setScore(scoreObject.getDouble("subject3"));
                    studentCourseScore3.setCourseId(181);
                    studentCourseScoreEntities.add(studentCourseScore3);

                    StudentCourseScoreEntity studentCourseScore4 = new StudentCourseScoreEntity();
                    studentCourseScore4.setExamId(examId);
                    studentCourseScore4.setStudentId(studentIds.get(0));
                    studentCourseScore4.setScore(scoreObject.getDouble("subject4"));
                    studentCourseScore4.setCourseId(182);
                    studentCourseScoreEntities.add(studentCourseScore4);

                    StudentCourseScoreEntity studentCourseScore5 = new StudentCourseScoreEntity();
                    studentCourseScore5.setExamId(examId);
                    studentCourseScore5.setStudentId(studentIds.get(0));
                    studentCourseScore5.setScore(scoreObject.getDouble("subject5"));
                    studentCourseScore5.setCourseId(183);
                    studentCourseScoreEntities.add(studentCourseScore5);

                    StudentCourseScoreEntity studentCourseScore6 = new StudentCourseScoreEntity();
                    studentCourseScore6.setExamId(examId);
                    studentCourseScore6.setStudentId(studentIds.get(0));
                    studentCourseScore6.setScore(scoreObject.getDouble("subject6"));
                    studentCourseScore6.setCourseId(184);
                    studentCourseScoreEntities.add(studentCourseScore6);

                    StudentCourseScoreEntity studentCourseScore7 = new StudentCourseScoreEntity();
                    studentCourseScore7.setExamId(examId);
                    studentCourseScore7.setStudentId(studentIds.get(0));
                    studentCourseScore7.setScore(scoreObject.getDouble("subject7"));
                    studentCourseScore7.setCourseId(185);
                    studentCourseScoreEntities.add(studentCourseScore7);

                    StudentCourseScoreEntity studentCourseScore8 = new StudentCourseScoreEntity();
                    studentCourseScore8.setExamId(examId);
                    studentCourseScore8.setStudentId(studentIds.get(0));
                    studentCourseScore8.setScore(scoreObject.getDouble("subject8"));
                    studentCourseScore8.setCourseId(186);
                    studentCourseScoreEntities.add(studentCourseScore8);

                    StudentCourseScoreEntity studentCourseScore9 = new StudentCourseScoreEntity();
                    studentCourseScore9.setExamId(examId);
                    studentCourseScore9.setStudentId(studentIds.get(0));
                    studentCourseScore9.setScore(scoreObject.getDouble("subject9"));
                    studentCourseScore9.setCourseId(187);
                    studentCourseScoreEntities.add(studentCourseScore9);


                }

            }
            studentScoreService.batchUpdateScore(studentCourseScoreEntities, scoreTableName);
        }
        return Msg.success();
    }




//    public static void main(String[] args) {
//        String s = "skdkdf.png";
//        System.out.println(s.substring(0,s.length() - 4));
//    }

}
